#include"outputbufferstream.h"
#include<errno.h>
#include<fcntl.h>
#include<iostream>
#include<cstdio>
#include<cstring>

void outputbufferstream::create(const char* fileName)
{
	this->fd = open(fileName, O_CREAT | O_TRUNC | O_RDWR, S_IRWXU);
	if(this->fd == -1)
		std::cout << "Error opening stream: " << strerror( errno ) << std::endl;
	else
		writeBuf = new int[BUFFER];
}

void outputbufferstream::close_s()
{
	if(this->wcount)
	{
		if(write(this->fd, this->writeBuf, this->wcount*sizeof(int)) < 0)
			std::cout << "Error writing to stream: " << strerror( errno ) << std::endl;
		this->writeBuf[0] = EOF;
		write(this->fd, this->writeBuf, sizeof(int));

	 	this->wcount = 0;
	}
	int ret = close(this->fd);
	if(ret < 0)
		std::cout << "Error closing stream: " << strerror( errno ) << std::endl;
	delete writeBuf;
}

void outputbufferstream::write_s(int data)
{
	if(this->wcount<BUFFER)
		this->writeBuf[this->wcount++] = data;
	else
	{
		if(write(this->fd, this->writeBuf, BUFFER*sizeof(int)) < 0)
			std::cout << "Error writing to stream: " << strerror( errno ) << std::endl;
		this->wcount = 0;
		this->writeBuf[this->wcount++] = data;
	}
}
